import time
import logging
from django.utils.deprecation import MiddlewareMixin

logger = logging.getLogger(__name__)


class RequestTimingMiddleware(MiddlewareMixin):
    """
    请求耗时统计中间件
    记录每个请求的处理时间并记录到日志
    """
    
    def process_request(self, request):
        """请求开始时的处理"""
        request.start_time = time.time()
        return None
    
    def process_response(self, request, response):
        """请求结束时的处理"""
        if hasattr(request, 'start_time'):
            duration = time.time() - request.start_time
            logger.info(
                f'Request: {request.method} {request.path} - '
                f'Duration: {duration:.4f}s - '
                f'Status: {response.status_code}'
            )
        return response
    
    def process_exception(self, request, exception):
        """异常处理"""
        if hasattr(request, 'start_time'):
            duration = time.time() - request.start_time
            logger.error(
                f'Request: {request.method} {request.path} - '
                f'Duration: {duration:.4f}s - '
                f'Exception: {str(exception)}'
            )
        return None
